/**
 * Created by 11450 on 2017/2/15.
 */

angular.module('NatureCloud').controller('BuildRunningDetailController', ["$scope", "$stateParams", "builderService","$interval","$timeout","$document", function ($scope, $stateParams, builderService,$interval,$timeout,$document) {
    var jobName = $stateParams.jobName;
    $scope.jobName = jobName;
    var buildSeq = $stateParams.buildSeq;
    $scope.buildSeq = buildSeq;
    $scope.buildConOut = '';
    var start = 0;
    var delay;
    var langTime;
    var interval = setTimeout(resContent,2000);

    $scope.scrollBottom = function () {
        var pageDiv = angular.element(document.getElementById("page"));
      jQuery(".main-content").scrollToElement(pageDiv,0,1500);
    };

    function resContent() {
        builderService.getBuildConOutRunning(jobName, buildSeq, start).then(function (response) {

            // $scope.buildConOut = $scope.buildConOut + response.data.data;
            var out = angular.element(document.getElementById('outcont'));
            var text = response.data.data;
            if(text !== ''){
                myFunction(text);
                delay = setTimeout(function () {
                    var pageDiv = angular.element(document.getElementById("page"));
                    jQuery(".main-content").scrollToElement(pageDiv,0,1500);
                },200);
            }

            var str = JSON.stringify(response.data.data);
            var length =  response.data.size;
            if (length === start){
                langTime = setTimeout(resContent,3000);
            }else{
                start = length;
                interval = setTimeout(resContent,2000);
            }
            if(str.indexOf('Finished: SUCCESS') >= 1 || str.indexOf('Finished: FAILURE') >= 1 || str.indexOf('Finished: ABORTED') >= 1){
                $scope.isHide = true;
                clearTimeout(interval);
                clearTimeout(delay);
                clearTimeout(langTime);
            }
        });
    }

    function myFunction(text) {
        // if(text !== ''){
            var node = document.createElement('DIV');
            var textnode = document.createTextNode(text);
            node.appendChild(textnode);
            document.getElementById("outcont").appendChild(node);
        // }
    }

    $scope.$on('$destroy', function(){
        if(interval){
            clearTimeout(interval);
            clearTimeout(delay);
            clearTimeout(langTime);
        }

    });




}]);
